package com.simplehc7878.auth.controller;

import com.simplehc7878.auth.security.jwt.JwtHelper;
import com.simplehc7878.auth.domain.model.User;
import com.simplehc7878.auth.service.UserService;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

@RequestMapping("/user/auth")
@RestController
public class UserAuthController {

    @Autowired
    private UserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Data
    public static class UserAuthDTO {
        @NotBlank(message = "用户名不能为空")
        private String username;
        @NotBlank(message = "密码不能为空")
        private String password;
    }

    @AllArgsConstructor
    @Data
    public static class UserAuthVO {
        private String token;
    }


    @PostMapping("/login")
    public UserAuthVO login(@Valid @RequestBody UserAuthDTO dto) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword()));
        String username = ((UserDetails) authentication.getPrincipal()).getUsername();
        return new UserAuthVO(jwtHelper.generateToken(username));
    }

    @PostMapping("/register")
    public void register(@Valid @RequestBody UserAuthDTO dto) {
        userService.create(new User(dto.getUsername().trim(), passwordEncoder.encode(dto.getPassword().trim())));
    }
}
